import minimist from "minimist"; // 用于解析参数
import esbuild from "esbuild";
import { fileURLToPath } from "node:url"; // 获取路径信息
import { dirname, resolve } from "node:path";
import { createRequire } from "node:module";
// console.log(process.argv); // [node.exe, dev.js, arg1, arg2, ...]
const argsinfo = process.argv.slice(2); // [arg1, arg2, arg3]
const args = minimist(argsinfo); // {_: ['reactivity'], f: "commonjs"}
// console.log(args);
const targets = args["_"].length == 0 ? ["reactivity", "shared"] : args["_"]; // ["reactivity"]
const target = args["_"][0] || "reactivity";
const format = args.f || "iife"; // commonjs

// 处理 __dirname 和 require
// 通过 fileURLToPath 来实现
const __dirname = dirname(fileURLToPath(import.meta.url));
const __filename = fileURLToPath(import.meta.url);
const require = createRequire(import.meta.url);
// console.log(targets);
targets.forEach((target) => {
  // 获取package文件
  const pkg = require(`../vuepackages/${target}/package.json`);

  // 入口文件  根据命令行提供的路径进行解析
  const entry = resolve(__dirname, `../vuepackages/${target}/src/index.ts`);

  esbuild
    .context({
      entryPoints: [entry],
      outfile: resolve(__dirname, `../vuepackages/${target}/dist/${target}.js`), // 出口
      bundle: true, // reactivity  --> shared  会打包在一起
      platform: "browser", // 打包后给浏览器使用
      sourcemap: true, // 可以调试源代码
      format, // iife, cjs, esm
      globalName: pkg.buildOptions?.name, // iife需要加上全局名称
    })
    .then((ctx) => {
      console.log("start dev");
      return ctx.watch(); // 监控入口文件进行持续打包处理
    });
});
